// ignore_for_file: unused_element

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:verse_systems/commom/config/config.dart';
import 'package:verse_systems/pages/login/login_control.dart';
import 'package:verse_systems/res/colors.dart';
import 'package:verse_systems/res/gaps.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/image_utils.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/widgets/TimerCountDownWidget.dart';
import 'package:verse_systems/widgets/alert.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
  final logic = Get.find<LoginControl>();
  final state = Get.find<LoginControl>().state;

  late final AnimationController _controller;
  late final Animation _animation;



  @override
  void dispose() {
    _controller.stop();
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);

    _animation = Tween<double>(
      begin: 320.w,
      end: 46.w,
    ).animate(
        CurvedAnimation(parent: _controller, curve: const Interval(0.3, 0.6)))
      ..addListener(() {
        if (_animation.isCompleted) {
          if (state.isLogin) {
            logic.hanldeGoToHome();
          }
        }
        setState(() {});
      });
  }

  Widget get _logo {
    return Container(
        margin: EdgeInsets.fromLTRB(10, 32.w, 10, 60.w),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(5.w),
              child:   Image.asset(
                  ImageUtils.getImgPath(Config.getConfigIcon()),
                  fit: BoxFit.fill,
                  width: 70.w,
                  height: 70.w,
                )
            )
        ,
            SizedBox(height: 19.w), 
            Text(
              "welcome_login".tr,
              style: TextStyle(
                color: Colours.app_main_text_color,
                fontSize: 24.sp,
              ),
            )
          ],
        ));
  }

  Widget get _accountTextFeild {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        margin: EdgeInsets.symmetric(
          horizontal: 30.w,
        ),
        height: 48.w,
        decoration: BoxDecoration(
            color: Colours.app_textField_background_color,
            border: Border.all(color: Colours.app_main_color, width: 0.8),
            borderRadius: BorderRadius.circular(8.w)),
        child: Row(
          children: [
            Text("+86",
                style: TextStyle(
                  color: Colours.app_black_text_color,
                  fontSize: 15.sp,
                )),
            Container(
              width: 1,
              color: Colours.app_line_color,
              margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
            ),
            Expanded(
                child: TextField(
              maxLength: 20,
              maxLines: 1,
              keyboardType: TextInputType.phone,
              inputFormatters: [
                FilteringTextInputFormatter(RegExp("[a-zA-Z0-9_.@]"),
                    allow: true)
              ],
              controller: logic.account,
              textAlign: TextAlign.left, //文本对齐方式
              style: TextStyle(
                fontSize: 15.sp,
                color: Colours.app_black_text_color,
              ),
              decoration: InputDecoration(
                  contentPadding: EdgeInsets.symmetric(vertical: 5.w),
                  border: InputBorder.none,
                  hintText: "please_enter_phone".tr,
                  counterText: '',
                  hintStyle: TextStyle(
                    fontSize: 15.sp,
                  )),
              showCursor: true,
              cursorColor: Colours.app_main_background_color,
              onChanged: (v) {
                state.mobileForCode = v;
              },
            ))
          ],
        ));
  }

  Widget get _passwordTextFeild {
    return Container(
        padding: EdgeInsets.only(left: 20.w),
        margin: EdgeInsets.symmetric(
          horizontal: 30.w,
        ),
        height: 48.w,
        decoration: BoxDecoration(
            color: Colours.app_textField_background_color,
            border: Border.all(color: Colours.app_main_color, width: 0.8),
            borderRadius: BorderRadius.circular(8.w)),
        child: Row(children: [
          Expanded(
              child: TextField(
            maxLength: 20,
            maxLines: 1,
            keyboardType: TextInputType.text,
            inputFormatters: [
              FilteringTextInputFormatter(RegExp("[a-zA-Z0-9_.@]"), allow: true)
            ],
            controller: logic.password,
            textAlign: TextAlign.left,
            style:
                TextStyle(fontSize: 15.sp, color: Colours.app_black_text_color),
            decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(vertical: 5.w),
                border: InputBorder.none,
                hintText: "please_enter_code".tr,
                counterText: '',
                hintStyle: TextStyle(
                  fontSize: 15.sp,
                )),
            showCursor: true,
            cursorColor: Colours.app_main_background_color,
          )),
          Obx(() {
            return TimerCountDownWidget(state.mobileForCode,
                onTimerFinish: () {});
          })
        ]));
  }

  Widget get _userxieyi {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 30.w,
          height: 30.w,
          child: Obx(() {
            return Checkbox(
                value: state.agreementIsChecked,
                activeColor: Colours.app_main_background_color,
                checkColor: Colours.app_main_color,
                hoverColor: Colours.app_main_background_color,
                shape: const CircleBorder(),
                onChanged: (v) {
                  if (v == true) {}
                  state.agreementIsChecked = v ?? true;
                });
          }),
        ),
        Gaps.hGap4,
        RichText(
            text: TextSpan(children: [
          TextSpan(
            text: 'read_and_agreed'.tr,
            style: TextStyle(
              color: Colours.color_99,
              fontSize: 12.sp,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                state.agreementIsChecked = !state.agreementIsChecked;
              },
          ),
          TextSpan(
            text: '《${"service_agreement".tr}》',
            style: TextStyle(
              color: Colours.blue_text_color,
              fontSize: 12.sp,
            ),
            recognizer: TapGestureRecognizer()..onTap = logic.handleProtocol,
          ),
          TextSpan(
            text: 'and'.tr,
            style: TextStyle(
              color: Colours.color_99,
              fontSize: 12.sp,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                state.agreementIsChecked = !state.agreementIsChecked;
              },
          ),
          TextSpan(
            text: '《${"privacy_policy".tr}》',
            style: TextStyle(
              color: Colours.blue_text_color,
              fontSize: 12.sp,
            ),
            recognizer: TapGestureRecognizer()..onTap = logic.handlePrivacy,
          )
        ]))
      ],
    );
  }

  void login() async {
    if (logic.account.text.trim() == '') {
      return Loading.showError("please_enter_phone".tr);
    }

    if (logic.password.text.trim() == '') {
      return Loading.showError("please_enter_code".tr);
    }

    bool? isFirstOpen = await AccountUtil.getAppIsFirstOpen();
    if (isFirstOpen) {
      logic.hanldeShowPolicy();
      return;
    }

    if (!state.agreementIsChecked) {
      Alert.showAlert(
          title: "tips".tr,
          confirm: "agree".tr,
          cancel: "cancel".tr,
          content: "please_check_agree_agreement".tr,
          onPressed: (() {
            state.agreementIsChecked = true;
            logic.hanldeUserLogin(showError: playReset);
            playAnimate(false);
          }));
      return;
    }

    logic.hanldeUserLogin(showError: playReset);
    playAnimate(false);
  }

  void playReset() async {
    _controller.reset();
  }

  Future playAnimate(bool isLogin) async {
    try {
      if (isLogin) {
        await _controller.forward();
      } else {
        await _controller.forward();
        await _controller.reverse();
      }
    } on TickerCanceled {
      // 自己处理动画取消
    }
  }

  Widget get _loginButton {
    return InkWell(
      onTap: login,
      child: Container(
        height: 48.w,
        width: _animation.value,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(24.w)),
          color: Colours.app_main_background_color,
        ),
        alignment: Alignment.center,
        child: _animation.value > 75
            ? Text("login".tr,
                style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                    color: Colours.app_main_color))
            : CircularProgressIndicator(
                valueColor:
                    const AlwaysStoppedAnimation<Color>(Colours.app_main_color),
                strokeWidth: 3.w,
              ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Scaffold(
            backgroundColor: Colours.app_main_color,
            appBar:
                AppBar(backgroundColor: Colours.app_main_color, elevation: 0),
            body: SingleChildScrollView(
                child: Container(
              decoration: const BoxDecoration(
                color: Colours.app_main_color,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  _logo,
                  _accountTextFeild,
                  Gaps.vGap16,
                  _passwordTextFeild,
                  // Gaps.vGap16,
                  // _forgotButton,
                  Gaps.vGap50,
                  _loginButton,
                  Gaps.vGap36,
                  _userxieyi
                ],
              ),
            ))));
  }
}
